﻿#region 信息

// CodeName: SoMcCoffee\Sohobloo.SoPermission.Console\Program.cs
// Copyright: Rex(sohobloo@163.com)
// CreateTime: 2014/01/26 15:02
// UpdateTime: 2014/01/26 16:01

#endregion

#region 引用

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;
using Sohobloo.SoCommon.CommonExtension;
using Sohobloo.SoCommon.Log;
using Sohobloo.SoPermission.Data.Initialization;
using Sohobloo.SoPermission.Entity;
using Sohobloo.SoPermission.Service;

#endregion

namespace Sohobloo.SoPermission.Console
{
    [Export]
    internal class Program : ILoggable
    {
        private static CompositionContainer _container;

        [Import]
        public IGroupService GroupService { get; set; }

        [Import]
        public ILogger Logger { get; set; }

        private static void Main(string[] args)
        {
            RegisterContainer();
            LogInitializer.Initialize();
            DbInitializer.Initialize();

            TestAdd();
            TestQuery();

            TestLog();

            System.Console.ReadKey();
        }

        private static void RegisterContainer()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(Directory.GetCurrentDirectory()));
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            _container = new CompositionContainer(catalog);
        }

        private static void TestAdd()
        {
            var program = _container.GetExportedValue<Program>();
            program.GroupService.Add(new Group
            {
                Name = "New"
            });
        }

        private static void TestQuery()
        {
            var program = _container.GetExportedValue<Program>();
            var list = program.GroupService.GetList();
            foreach (var g in list)
            {
                System.Console.WriteLine("Group:{0}, UpdateTime:{1}, UpdateUser:{2}", g.Name, g.UpdateTime, g.UpdateUser);
                if (g.Accounts.IsNotNull())
                {
                    foreach (var a in g.Accounts)
                    {
                        System.Console.WriteLine("Account:" + a.UserName);
                    }
                }
            }
        }

        private static void TestLog()
        {
            var program = _container.GetExportedValue<Program>();
            program.LogInfo("123");
            try
            {
                string a = null;
                a.ToString();
            }
            catch(Exception ex)
            {
                program.LogError(ex);
            }
        }
    }
}